/*
 * Copyright (c) 2017. danlu.com Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.delivery.order.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.util.CommonUtils;

import static cn.com.dhc.danlu.util.CommonConst.MyOrderConst.BTN_HAS;
import static cn.com.dhc.danlu.util.CommonConst.MyOrderConst.BTN_NO;

/**
 * author: wuhaiyang(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-03-02 下午5:44<br/>
 *
 * <p>
 * 订单操作视图
 * </p>
 */
public class OrderFunctionView extends RelativeLayout {
    /**
     * 是否是订单详情
     */
    private boolean isOrderDetail = false;
    private String buttonList;
    private OnClickListener orderOperatorCallback;

    public OrderFunctionView(Context context) {
        this(context, null);
    }

    public OrderFunctionView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public OrderFunctionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.OrderFunctionView);
        isOrderDetail = array.getBoolean(R.styleable.OrderFunctionView_isOrderDetail, false);
        array.recycle();
    }

    public void setOrderOperatorCallback(OnClickListener orderOperatorCallback) {
        this.orderOperatorCallback = orderOperatorCallback;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    public void refreshButton(String buttomList) {
        try {
            removeAllViews();
            // 后期增加需求 ： 同意&拒绝取消 情况 特殊处理 一个字符决定两个按钮的显示逻辑
            int showCount = buttomList.length() - getNotShowBtnCount(buttomList, 0);
            if (showCount == 0) {
                return;
            }
            this.buttonList = buttomList;
            String[] split = buttomList.split("");

            // 权重分级：付款 | 确认收货 >  取消交易 | 同意&拒绝取消交易（需求未澄清） > 更多操作
            boolean isShowPay = split[1].equals(BTN_HAS);
            boolean isReceive = split[3].equals(BTN_HAS);
            boolean isCancel = (!split[4].equals(BTN_NO) && !split[4].equals("4")) && isOrderDetail;
            boolean isShowAgreenCancel = false;
            boolean isShowRefuseCancel = false;
            boolean isShowMore = split[8].equals(BTN_HAS) || split[6].equals(BTN_HAS) || split[9].equals(BTN_HAS);
            if (isShowPay) {
                attachChildView(R.id.btn_order_pay, R.string.order_pay, R.drawable.selector_order_operation, R.color.white);
            }
            if (isReceive) {
                attachChildView(R.id.btn_order_receive, R.string.order_confirm_receive, R.drawable.selector_order_operation, R.color.white);
            }
            if (isCancel) {
                attachChildView(R.id.btn_order_cancel, R.string.order_cancel_deal, R.drawable.selector_order_trackbtn, R.drawable.selector_btn_order_tracktxt);
            }
            if (isShowAgreenCancel) {
                //            attachChildView(R.id.btn_order_agreen_cancel, R.string.order_agreen_cancel);
            }
            if (isShowRefuseCancel) {
                //            attachChildView(R.id.btn_order_refuse_cancel, R.string.order_refuse_cancel);
            }
            if (isShowMore) {
                attachChildView(R.id.btn_more_ope, R.string.order_more_oper, -1, -1);
            }
        } catch (Exception ignored) {

        }
    }

    public void attachChildView(int id, int strId, int backResId, int textColorResId) {
        View btn = createBtn(id, strId, backResId, textColorResId);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(CommonUtils.dipToPx(getContext(), 80), CommonUtils.dipToPx(getContext(), 30));
        int rightViewId = findRightViewId();
        if (-1 != rightViewId) {
            lp.addRule(LEFT_OF, rightViewId);
            lp.rightMargin = (int) getResources().getDimension(R.dimen.dl_25);
        } else {
            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        }
        addView(btn, lp);
    }

    private int findRightViewId() {
        View view = getChildAt(getChildCount() - 1);
        return null != view ? view.getId() : -1;
    }

    private View createBtn(int id, int str, int backResourceId, int textColorResourceId) {
        if (id == R.id.btn_more_ope) {
            OrderMoreOperationBtn moreView = new OrderMoreOperationBtn(getContext());
            moreView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String[] split = buttonList.split("");
                    String innerList = split[8] + split[9] + split[6];
                    MoreOperatePopupView popupView = new MoreOperatePopupView(getContext(), orderOperatorCallback, innerList);
                    popupView.showAtLocation(findParent(), Gravity.BOTTOM, 0, 0);
                }
            });
            moreView.setOpname(str);
            return moreView;
        } else {
            Button btn = new Button(getContext());
            btn.setId(id);
            btn.setText(str);
            btn.setGravity(Gravity.CENTER);
            int padding = CommonUtils.dipToPx(getContext(), 5);
            btn.setPadding(0, padding, 0, padding);
            btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            btn.setBackgroundResource(backResourceId);
            btn.setTextColor(getContext().getResources().getColorStateList(textColorResourceId));
            btn.setOnClickListener(orderOperatorCallback);
            return btn;
        }
    }

    private View findParent() {
        Activity activity = CommonUtils.getActivity(this);
        return activity.getWindow().getDecorView();
    }

    /**
     * 获取不显示按钮个数
     */
    private int getNotShowBtnCount(String buttonList, int preCount) {
        int length = buttonList.length();
        if (!buttonList.contains(BTN_NO)) {
            return preCount;
        }
        return getNotShowBtnCount(buttonList.substring(buttonList.indexOf(BTN_NO) + 1, length), ++preCount);
    }
}
